const { exec, escapeAndXSS } = require('../db/mysql')

const getList = async (author, keyword) => {

  let sql = `select id, title, content, author, createtime from blogs where 1=1 `
  if (author) {
    author = escapeAndXSS(author)
    sql += `and author='${author}'`
  }
  if (keyword) {
    keyword = escapeAndXSS(keyword)
    sql += `and title like '%${keyword}%' `
  }
  sql += ` order by createtime desc;`

  return await exec(sql)
}

const getDetail = async (id) => {
  id = escapeAndXSS(id)
  let sql = `select id, title, content, author, createtime from blogs where id='${id}' `

  const rows = await exec(sql)

  // 查询详情，将数组变成对象
  return rows[0]
}

const newBlog = async (blogData = {}) => {
  // blogData 是一个博客对象，包含title content
  const title = escapeAndXSS(blogData.title)
  const content = escapeAndXSS(blogData.content)
  const author = escapeAndXSS(blogData.author)
  const createtime = Date.now()

  const sql = `
    insert into blogs (title, content, createtime, author)
    values ('${title}', '${content}', '${createtime}', '${author}')
  `

  const inserData = await exec(sql)

  return {
    id: inserData.insertId
  }
}

const updateBlog = async (id, blogData = {}) => {
  id = escapeAndXSS(id)
  const title = escapeAndXSS(blogData.title)
  const content = escapeAndXSS(blogData.content)

  const sql = `
    update blogs set title='${title}', content='${content}' where id='${id}'
  `

  const updateData = await exec(sql)

  if (updateData.affectedRows > 0) {
    return true
  }
  return false
}

const delBlog = async (id, author) => {
  id = escapeAndXSS(id)
  author = escapeAndXSS(author)

  const sql = `delete from blogs where id='${id}' and author='${author}'`
  const deleteData = await exec(sql)
  
  if (deleteData.affectedRows > 0) {
    return true
  }
  return false
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
}
